<?php

namespace app\admin\controller;

use app\common\model\Users;
use think\Request;

class User extends Base
{

    public function index(Request $request)
    {
        if ( $request->isAjax() ){

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);
            $data = array(
                'data'      => Users::field('password', true)->order(['id'=>'desc'])->page($page)->limit($limit)->select(),
                'count'     => Users::count('id'),
                'code'      => 0,
                'msg'       => '',
            );
            return json($data);
        }
        return view();
    }


    // 添加域名
    public function create(Request $request)
    {
        if ( $request->isPost() ){
            $post = trimAll($request->post());
            $post['status'] = isset($post['status']) ? $post['status'] : 2;

            $post['password'] = sha1_password($post['password']);
            if ( Users::create($post) ){
                createLog('添加用户成功：' . $post['username']);
                success('保存成功');
            }else{
                createLog('添加用户失败');
                error('保存失败');
            }
        }
        return view();
    }

    public function edit(Request $request, $id)
    {
        if ( $request->isPost() ){
            $post = trimAll($request->post());
            $post['status'] = isset($post['status']) ? $post['status'] : 2;

            if ( $post['password'] ){
                $post['password'] = sha1_password($post['password']);
            } else {
				unset($post['password']);
            }

            if ( Users::where('id', $id)->update($post) ){
                createLog('编辑用户成功' . $post['username']);
                success('保存成功');
            } else {
                createLog('编辑用户失败' . $post['username']);
                error('保存失败');
            }
        }
        $data = Users::get($id);
        $this->assign('data', $data);
        return view();
    }


	// 续费
	public function xufei(Request $request)
	{
		if ($request->isPost()){
			$id = $request->post('id');
			$tian = (int)$request->post('tian');
			if ( !$tian ) error('请输入正确的数字（不能为0）');

			// 获取用户信息
			$user = Users::field('password', true)->get($id);

			// 如果用户已过期，从当前时间开始计算
			if ( (int)$user['end_time'] < time() ){
				$user->end_time = time() + 60*60*24*$tian;
				$user->save();
			} else {
				$user->end_time = $user->end_time + 60*60*24*$tian;
				$user->save();
			}
			success('充值成功');
		}
	}

}
